<?php
/**
 * 
 * @author huangjian E-mail:870596179@qq.com
 * @version 创建时间：2016年11月1日 上午10:08:23 
 * 类说明
 */
class ProductAction extends BaseAction{
	/**
	 * @authority 浏览
	 */
	public function index(){
		$TypeModel = M("Type");
		$map['reserve'] = 1;
		$map['flag'] = 1;
		$types = $TypeModel->where($map)->field("id,type_name as name")->order("seq asc")->select();
		$this->assign("types",$types);
		$this->display('index');
	}
	
	//列表
	public function getAllData(){
		$Model = D('ProductView');
		$map = $this->loadSeachCondition();
		$map['flag'] = 1;
		$map['Type.flag'] = 1;
		$map['Subtype.flag'] = 1;
		$map['create_userid'] = $_SESSION['USER_ADMIN_KEY_ID'];
		$total = $Model->where($map)->count();// 查询满足要求的总记录数
		$page = json_decode($this->pageParam($total));
		$sort = $page->sort;
		$data = $Model->where($map)->limit($page->firstRow,$page->listRows)->order($sort)->select();
		$vo = $this->toJosnForGird($data,$page);
		echo json_encode($vo);
	}
	
	/**
	 * 组装条件
	 * @return multitype:multitype:string
	 */
	public function loadSeachCondition(){
		$map = array();
		if(!empty($_GET['name'])){
			$map['name'] = array("like","%".$_GET['name']."%");
		}
		if(!empty($_GET['type_id'])){
			$map['type_id'] = $_GET['type_id'];
		}
		if(!empty($_GET['subtype_code'])){
			$map['subtype_code'] = $_GET['subtype_code'];
		}
		return $map;
	}

	/**
	 * @authority 新增
	 */
	public function add(){
		$TypeModel = M("Type");$SubtypeModel = M("Subtype");
		$map['reserve'] = 1;
		$map['flag'] = 1;
		$types = $TypeModel->where($map)->field("id,type_name")->order("seq asc")->select();
		$where['parent_id'] = $types[0]['id'];
		$where['flag'] = 1;
		$subtypes = $SubtypeModel->where($where)->field("subtype_code,subtype_name")->order("seq asc")->select();
		$this->assign("types",$types);
		$this->assign("subtypes",$subtypes);
		$this->display('add');
	}
	
	/**
	 * 插入
	 */
	public function insert(){
		$Model = M($this->getActionName());
		unset ( $_POST [$Model->getPk()] );
		if (false === $Model->create()) {
			$this->error($Model->getError());
		}
		$data = $Model->create();
		//查询最大排序
		$map['flag'] = 1;
		$max_seq = $Model->where($map)->order('seq desc')->getField('seq');
		$data['seq'] = $max_seq + 1;
		$data['create_userid'] = $this->uid;
		//保存当前数据对象
		if ($result = $Model->add($data)) { //保存成功
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_ADD_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_ADD_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改
	 */
	public function edit() {
		$Model = M($this->getActionName());
		$map[$Model->getPk()] = $_REQUEST['id'];
		$map['create_userid'] = $this->uid;
		$vo = $Model->where($map)->find();
		if(empty($vo)){
			checkStop();
		}
		$vo['contents'] = explode("|",$vo['content']);
		$TypeModel = M("Type");$SubtypeModel = M("Subtype");
		$condition['reserve'] = 1;
		$condition['flag'] = 1;
		$types = $TypeModel->where($condition)->field("id,type_name")->order("seq asc")->select();
		$where['parent_id'] = $vo['type_id'];
		$where['flag'] = 1;
		$subtypes = $SubtypeModel->where($where)->field("subtype_code,subtype_name")->order("seq asc")->select();
		$this->assign("types",$types);
		$this->assign("subtypes",$subtypes);
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * 更新
	 */
	public function update() {
		$Model = M($this->getActionName());
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		$where['id'] = $Model->id;
		$where['create_userid'] = $this->uid;
		// 更新数据
		if(false != $Model->where($where)->save()) {
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	/**
	 * 更改状态
	 */
	public function updateStatus() {
		//删除指定记录
		$Model = M($this->getActionName());
		$MeetingplaceProductModel = M("Meetingplace_product");
		$pk = $Model->getPk();
		$id = $_REQUEST[$pk];
		if (isset($id)) {
			$where['product_id'] = $id;
			$count = $MeetingplaceProductModel->where($where)->count();
			if($count !=0){
				$this->ajaxReturn(0,"该商品已绑定会场，请删除后操作！",0);
			}
			$condition = array($pk => array('in', explode(',', $id)));
			$condition['create_userid'] =$this->uid;
			if (false !== $Model->where($condition)->setField($_REQUEST['field'],$_REQUEST['islock'])) {
				$this->deleteSession();
				$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
			} else {
				$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
			}
		}
	}
	
	/**
	 * 逻辑删除
	 */
	public function logicDel(){
		$Model = M($this->getActionName());
		$MeetingplaceProductModel = M("Meetingplace_product");
		if (!empty($Model)) {
			$pk = $Model->getPk();
			$id = $_REQUEST[$pk];
			if (isset($id)) {
				$where['product_id'] = $id;
				$count = $MeetingplaceProductModel->where(array("product_id" => array('in', $id)))->count();
				if($count !=0){
					$this->ajaxReturn(0,"该商品已绑定会场，请删除后操作！",0);
				}
				$condition = array($pk => array('in', $id));
				$condition['create_userid'] = $this->uid;
				if (false !== $Model->where($condition)->setField('flag',2)) {
					$this->deleteSession();
					$this->ajaxReturn(1,L('ADMIN_DELETE_SUCCESS'),1);
				} else {
					$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
				}
			} else {
				$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
			}
		}
	}
	
	//配置产品
	public function cog(){
		$this->display();
	}
	
	/**
	 * 获取小类
	 */
	public function getSubtypes(){
		$SubtypeModel = M('Subtype');
		$id = $_REQUEST["id"];
		$vo = $SubtypeModel->where("flag = 1 and parent_id=".$id)->field("subtype_code,subtype_name")->order("seq asc")->select();
		$this->ajaxReturn($vo,1,0);
	}
	
	/**
	 * @authority 修改排序
	 */
	public function editSeq() {
		$TypeModel = M("Type");$SubtypeModel = M("Subtype");
		$condition['reserve'] = 1;
		$condition['flag'] = 1;
		$types = $TypeModel->where($condition)->field("id,type_name")->order("seq asc")->select();
		$where['parent_id'] = $types[0]['id'];
		$where['flag'] = 1;
		$subtypes = $SubtypeModel->where($where)->field("subtype_code,subtype_name")->order("seq asc")->select();
		$this->assign("types",$types);
		$this->assign("subtypes",$subtypes);
		$this->display();
	}
	
	/**
	 * 获取排序的字段
	 */
	public function getNodes(){
		$Model = M($this->getActionName());
		$map['flag'] = 1;
		$map['type_id'] = $_POST['type_id'];
		$map['create_userid'] = $this->uid;
		$data = $Model->where($map)->order('seq asc')->field('id,name')->select();
		$newData = array();
		$newData[0]['id'] = -1;
		$newData[0]['pId'] = 0;
		$newData[0]['name'] = $_POST['name'];
		$newData[0]['isParent'] = true;
		$newData[0]['open'] = true;
		for($i=0; $i<count($data); $i++) {
			$newData[$i+1]['id'] = $data[$i]['id'];
			$newData[$i+1]['pId'] = $newData[0]['id'];
			$newData[$i+1]['name'] = $data[$i]['name'];
		}
		$this->ajaxReturn($newData,'',1);
	}
	/**
	 * @authority 更新排序
	 */
	public function updateSeq(){
		$Model = M($this->getActionName());
		//批量更新
		$seq = $_REQUEST['seq'];
		$sql .= 'SET seq = CASE id ';
		foreach ($seq as $key=>$val){
			$ids .= $val.",";
			$key++;
			$sql .= ' WHEN '.$val.' THEN '.$key." ";
		}
		$sql .= ' END ';
		$ids = substr($ids,0,strlen($ids)-1);
		$sql .= 'where id in ('.$ids.')';
		$where['id'] = array('in',$ids);
		$where['create_userid'] = $this->uid;
		$data['_query'] = $sql;
		$result = $Model->execute('update __TABLE__ '.$sql);
		if($result !== false){
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_SEQ_SUCCESS'),1);
		}else{
			$this->ajaxReturn(0,L('ADMIN_SEQ_ERROR'),0);
		}
	}
	
	//图片传图
	public function uploadImg(){
		$folderName = $_POST['folderName'];//格式  首字母大写
		$prefix = $_POST['prefix'];//格式  m_,s_
		$maxWidth = $_POST['maxWidth'];//格式500,200
		$maxHeight = $_POST['maxHeight'];//格式500,200
		import('ORG.Net.UploadFile');
		$targetFolder_b = './Uploads/'.$folderName.'/'.date('Y-m-d').'/';
		if(!is_dir($targetFolder_b)){
			@mkdir($targetFolder_b,0777);
		}
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  $targetFolder_b;// 设置附件上传目录
		if($maxWidth != 0 && $maxHeight != 0){
			$upload->thumb = true;
			$upload->thumbPrefix = $prefix;  //缩略图前缀
			$upload->thumbMaxWidth = $maxWidth;
			$upload->thumbMaxHeight = $maxHeight;
			$upload->thumbType = 0;//按设置大小截取 0 按原图等比例缩略
			$upload->thumbRemoveOrigin = true; //上传后移除原图
		}
		if(!$upload->upload()) {// 上传错误提示错误信息
			$this->ajaxReturn(0,$upload->getErrorMsg(),0);
		}else{// 上传成功
			$info =  $upload->getUploadFileInfo();
			//补上缩略图的前缀
			if($maxWidth != 0 && $maxHeight != 0){
				$bak['url'] = ltrim($info[0]['savepath'],".").$prefix.$info[0]['savename'];
			}else{
				$bak['url'] = ltrim($info[0]['savepath'],".").$info[0]['savename'];
			}
			$bak['localname'] = $info[0]['name'];
			$this->ajaxReturn($bak,'上传成功！',1);
		}
	}
	
	private function deleteSession(){
		//版本号
		if(!S('S_PRODUCT_VERSION')){
			S('S_PRODUCT_VERSION',10000);
		}else{
			S('S_PRODUCT_VERSION',S('S_PRODUCT_VERSION')+1);
		}
		S('S_PRODUCT',null);
	}
}